<template>
  <div 
    class="article-card" 
    :class="{ 'article-card--clickable': clickable }"
    @click="handleClick"
  >
    <!-- 文章头部 -->
    <div class="article-header">
      <div class="article-number">
        {{ article.article_number }}
      </div>
      <div class="article-actions">
        <!-- 收藏按钮 -->
        <button
          v-if="showFavorite"
          :class="[
            'favorite-btn',
            { 'favorite-btn--active': isFavorited }
          ]"
          :disabled="favoriteLoading"
          @click.stop="toggleFavorite"
        >
          <HeartIcon 
            :class="[
              'w-5 h-5',
              isFavorited ? 'text-red-500' : 'text-gray-400'
            ]"
            :fill="isFavorited ? 'currentColor' : 'none'"
          />
        </button>
        
        <!-- 更多操作 -->
        <button
          v-if="showMenu"
          class="menu-btn"
          @click.stop="toggleMenu"
        >
          <EllipsisVerticalIcon class="w-5 h-5 text-gray-400" />
        </button>
      </div>
    </div>
    
    <!-- 章节信息 -->
    <div
      v-if="article.chapter_info"
      class="chapter-info"
    >
      <span class="chapter-badge">
        {{ article.chapter_info.part }}
      </span>
      <span
        v-if="article.chapter_info.chapter_title"
        class="chapter-title"
      >
        {{ article.chapter_info.chapter_title }}
      </span>
    </div>
    
    <!-- 文章内容 -->
    <div
      class="article-content"
      :class="fontSizeClass"
    >
      <p class="content-text">
        {{ truncatedContent }}
      </p>
      
      <!-- 展开/收起按钮 -->
      <button
        v-if="article.content && article.content.length > maxContentLength"
        class="expand-btn"
        @click.stop="toggleExpanded"
      >
        {{ isExpanded ? '收起' : '展开' }}
        <ChevronDownIcon 
          :class="[
            'w-4 h-4 ml-1 transition-transform',
            { 'rotate-180': isExpanded }
          ]"
        />
      </button>
    </div>
    
    <!-- 法条解释 -->
    <div 
      v-if="article.explanation && (showExplanation || isExpanded)" 
      class="article-explanation"
      :class="fontSizeClass"
    >
      <div class="explanation-header">
        <BookOpenIcon class="w-4 h-4 text-blue-500 mr-1" />
        <span class="text-sm font-medium text-blue-700">法条解释</span>
      </div>
      <p class="explanation-text">
        {{ isExpanded ? article.explanation : truncatedExplanation }}
      </p>
    </div>
    
    <!-- 关键词标签 -->
    <div
      v-if="article.keywords && article.keywords.length > 0"
      class="keywords"
    >
      <span
        v-for="keyword in displayKeywords"
        :key="keyword"
        class="keyword-tag"
        @click.stop="$emit('keyword-click', keyword)"
      >
        {{ keyword }}
      </span>
    </div>
    
    <!-- 文章底部信息 -->
    <div
      v-if="showMeta"
      class="article-meta"
    >
      <div class="meta-item">
        <CalendarIcon class="w-4 h-4 text-gray-400 mr-1" />
        <span class="text-xs text-gray-500">
          {{ formatDate(article.created_at) }}
        </span>
      </div>
    </div>
    
    <!-- 操作菜单 -->
    <div
      v-if="showMenuDropdown"
      class="menu-dropdown"
      @click.stop
    >
      <button
        v-for="action in menuActions"
        :key="action.key"
        class="menu-item"
        @click="handleMenuAction(action)"
      >
        <component
          :is="action.icon"
          class="w-4 h-4 mr-2"
        />
        {{ action.label }}
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import {
  HeartIcon,
  BookOpenIcon,
  CalendarIcon,
  EllipsisVerticalIcon,
  ChevronDownIcon,
  ShareIcon,
  DocumentDuplicateIcon,
  LinkIcon
} from '@heroicons/vue/24/outline'
import { useAppStore } from '@/stores/app'
import { logger } from '@/utils/logger'

const props = defineProps({
  article: {
    type: Object,
    required: true
  },
  clickable: {
    type: Boolean,
    default: true
  },
  showFavorite: {
    type: Boolean,
    default: true
  },
  showExplanation: {
    type: Boolean,
    default: false
  },
  showMenu: {
    type: Boolean,
    default: false
  },
  showMeta: {
    type: Boolean,
    default: false
  },
  maxContentLength: {
    type: Number,
    default: 200
  },
  maxKeywords: {
    type: Number,
    default: 5
  }
})

const emit = defineEmits([
  'click',
  'favorite-toggle',
  'keyword-click',
  'share',
  'copy'
])

// 响应式数据
const isExpanded = ref(false)
const isFavorited = ref(false)
const favoriteLoading = ref(false)
const showMenuDropdown = ref(false)

// Store
const appStore = useAppStore()

// 计算属性
const fontSizeClass = computed(() => appStore.fontSize)

const truncatedContent = computed(() => {
  if (!props.article.content) return ''
  
  if (isExpanded.value || props.article.content.length <= props.maxContentLength) {
    return props.article.content
  }
  
  return props.article.content.substring(0, props.maxContentLength) + '...'
})

const truncatedExplanation = computed(() => {
  if (!props.article.explanation) return ''
  
  if (isExpanded.value || props.article.explanation.length <= props.maxContentLength) {
    return props.article.explanation
  }
  
  return props.article.explanation.substring(0, props.maxContentLength) + '...'
})

const displayKeywords = computed(() => {
  if (!props.article.keywords) return []
  return props.article.keywords.slice(0, props.maxKeywords)
})

const menuActions = computed(() => [
  {
    key: 'share',
    label: '分享',
    icon: ShareIcon
  },
  {
    key: 'copy',
    label: '复制',
    icon: DocumentDuplicateIcon
  },
  {
    key: 'link',
    label: '复制链接',
    icon: LinkIcon
  }
])

// 事件处理
const handleClick = () => {
  if (props.clickable) {
    logger.userAction('点击文章卡片', { articleNumber: props.article.article_number })
    emit('click', props.article)
  }
}

const toggleExpanded = () => {
  isExpanded.value = !isExpanded.value
  logger.userAction('切换文章展开状态', { 
    articleNumber: props.article.article_number,
    expanded: isExpanded.value 
  })
}

const toggleFavorite = async () => {
  if (favoriteLoading.value) return
  
  try {
    favoriteLoading.value = true
    isFavorited.value = !isFavorited.value
    
    logger.userAction('切换收藏状态', { 
      articleNumber: props.article.article_number,
      favorited: isFavorited.value 
    })
    
    emit('favorite-toggle', {
      article: props.article,
      favorited: isFavorited.value
    })
  } catch (error) {
    // 回滚状态
    isFavorited.value = !isFavorited.value
    logger.error('切换收藏状态失败:', error)
  } finally {
    favoriteLoading.value = false
  }
}

const toggleMenu = () => {
  showMenuDropdown.value = !showMenuDropdown.value
}

const handleMenuAction = (action) => {
  showMenuDropdown.value = false
  
  logger.userAction('文章菜单操作', { 
    action: action.key,
    articleNumber: props.article.article_number 
  })
  
  emit(action.key, props.article)
}

// 工具函数
const formatDate = (dateString) => {
  if (!dateString) return ''
  
  try {
    const date = new Date(dateString)
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'short',
      day: 'numeric'
    })
  } catch {
    return ''
  }
}

// 监听点击外部关闭菜单
const handleClickOutside = (event) => {
  if (!event.target.closest('.article-card')) {
    showMenuDropdown.value = false
  }
}

// 生命周期
import { onMounted, onUnmounted } from 'vue'

onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>
.article-card {
  @apply bg-white border border-gray-200 rounded-lg p-4 shadow-sm;
  @apply transition-all duration-200;
  @apply relative;
}

.article-card--clickable {
  @apply cursor-pointer hover:shadow-md hover:border-gray-300;
}

.article-header {
  @apply flex items-center justify-between mb-3;
}

.article-number {
  @apply text-lg font-semibold text-gray-900;
}

.article-actions {
  @apply flex items-center space-x-2;
}

.favorite-btn {
  @apply p-1 rounded-full hover:bg-gray-100;
  @apply transition-colors duration-200;
  @apply disabled:opacity-50 disabled:cursor-not-allowed;
}

.favorite-btn--active {
  @apply hover:bg-red-50;
}

.menu-btn {
  @apply p-1 rounded-full hover:bg-gray-100;
  @apply transition-colors duration-200;
}

.chapter-info {
  @apply flex items-center space-x-2 mb-3;
}

.chapter-badge {
  @apply inline-flex px-2 py-1 text-xs font-medium;
  @apply bg-blue-100 text-blue-800 rounded-full;
}

.chapter-title {
  @apply text-sm text-gray-600;
}

.article-content {
  @apply mb-3;
}

.content-text {
  @apply text-gray-800 leading-relaxed mb-2;
}

.expand-btn {
  @apply inline-flex items-center text-sm text-blue-600;
  @apply hover:text-blue-800 font-medium;
}

.article-explanation {
  @apply bg-blue-50 border-l-4 border-blue-400 p-3 mb-3 rounded-r;
}

.explanation-header {
  @apply flex items-center mb-2;
}

.explanation-text {
  @apply text-gray-700 leading-relaxed;
}

.keywords {
  @apply flex flex-wrap gap-2 mb-3;
}

.keyword-tag {
  @apply inline-flex px-2 py-1 text-xs;
  @apply bg-gray-100 text-gray-700 rounded-full;
  @apply hover:bg-gray-200 cursor-pointer;
  @apply transition-colors duration-200;
}

.article-meta {
  @apply flex items-center justify-between pt-3 border-t border-gray-100;
}

.meta-item {
  @apply flex items-center;
}

.menu-dropdown {
  @apply absolute top-12 right-4 z-10;
  @apply bg-white border border-gray-200 rounded-lg shadow-lg;
  @apply min-w-32 py-1;
}

.menu-item {
  @apply w-full flex items-center px-3 py-2 text-sm text-gray-700;
  @apply hover:bg-gray-50 hover:text-gray-900;
  @apply transition-colors duration-200;
}

/* 响应式设计 */
@media (max-width: 640px) {
  .article-card {
    @apply p-3;
  }
  
  .article-number {
    @apply text-base;
  }
  
  .keywords {
    @apply gap-1;
  }
  
  .keyword-tag {
    @apply text-xs px-2 py-0.5;
  }
}
</style>
